/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package company.beans;

import facades.CandidateEconomicTypeFacade;
import facades.CandidateFacade;
import facades.CandidateTypeFacade;
import facades.CompanyAdquiredProfileFacade;
import facades.CompanyFacade;
import facades.UserFacade;
import facades.UserTypeFacade;
import entities.Candidate;
import entities.Company;
import entities.CompanyAdquiredProfile;
import entities.User;
import util.ImageStoreHelper;
import util.Sha256Encrypter;
import java.io.File;
import java.io.IOException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import entities.CompanyAdquiredProfileFolder;
import entities.CompanyFolder;
import entities.Search;
import facades.CompanyAdquiredProfileFolderFacade;
import facades.CompanyFolderFacade;
import facades.CompanyFolderTypeFacade;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
import javax.transaction.Transactional;
import qualifiers.CreatedEntityEvent;
import qualifiers.PreCreateEntityEvent;

/**
 *
 * @author damfercer
 */
@Named(value = "createCandidateForCompanyBean")
@SessionScoped
public class CreateCandidateForCompanyBean implements Serializable {
    @Inject
    UserFacade userFacade;
    @Inject
    CompanyFacade companyFacade;
    @Inject
    CandidateFacade candidateFacade;
    @Inject
    UserTypeFacade userTypeFacade;
    @Inject
    CandidateEconomicTypeFacade candidateEconomicTypeFacade;
    @Inject
    CandidateTypeFacade candidateTypeFacade;
    @Inject
    CompanyAdquiredProfileFacade companyAdquiredProfileFacade;
    @Inject
    CompanyFolderFacade companyFolderFacade;
    @Inject
    CompanyAdquiredProfileFolderFacade companyAdquiredProfileFolderFacade;
    @Inject
    CompanyFolderTypeFacade companyFolderFacadeType;
    @Inject
    @CreatedEntityEvent
    private Event<Candidate> newCandidateEvent;
    @Inject
    @PreCreateEntityEvent
    private Event<CompanyFolder> preCreateCompanyFolderEvent;
    @Inject
    @CreatedEntityEvent
    private Event<CompanyFolder> createdCompanyFolderEvent;
    @Inject
    @PreCreateEntityEvent
    private Event<CompanyAdquiredProfileFolder> preCreatedCompanyAdquiredProfileFolderEvent;
    @Inject
    @CreatedEntityEvent
    private Event<CompanyAdquiredProfileFolder> createdCompanyAdquiredProfileFolderEvent;
    @Inject
    @CreatedEntityEvent
    private Event<User> newUserEvent;
    private String companyId;
    private Company company;
    private Candidate candidate;

    /**
     * Creates a new instance of CreateCandidateForCompanyBean
     */
    public CreateCandidateForCompanyBean() {
    }
    

    /**
     * @return the companyId
     */
    public String getCompanyId() {
        return companyId;
    }

    /**
     * @param companyId the companyId to set
     */
    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }
    
    public String retrieveCompany(){
        if(companyId!=null){
            Integer idCompany;
            Company c;
            try{
                idCompany=new Integer(companyId);
                c=companyFacade.find(idCompany);
            }
            catch(Exception e){
                c=null;
            }
            if(c!=null){
                company=c;
                if(candidate==null){
                    candidate=new Candidate();
                    if(candidate.getUser()==null){
                        candidate.setUser(new User());
                    }
                    candidate.getUser().setUserType(userTypeFacade.find(1));
                    candidate.getUser().setRelatedUser(c.getIdUser());
                }
                return null;
            }
            else{
                return "/index.xhtml";  
            }
        }
        else{
            return "/index.xhtml";
        }
    }
    
    @Transactional
    public String createCandidate() throws IOException{
        persistCandidate();
        makeDirs();
        CompanyAdquiredProfile profile=new CompanyAdquiredProfile();
        profile.setAdquisitionDate(new Date());
        profile.setCandidate(candidate);
        profile.setCompany(company);
        //profile.setFolder(null);
        profile.setIsPayed(false);
        profile.setPayDate(null);
        profile.setPrice(BigDecimal.ZERO);
        companyAdquiredProfileFacade.create(profile);
        //Sacamos la carpeta de tipo 2 de la compañía
        CompanyFolder workWithUs=companyFolderFacade.findFolderWorkWithUs(company.getIdCompany());
        if(workWithUs==null){
            workWithUs=createFolderWorkWithUs(company);
        }
        CompanyAdquiredProfileFolder profileFolder=new CompanyAdquiredProfileFolder();
        profileFolder.setCompanyAdquiredProfile(profile);
        profileFolder.setCompanyFolder(workWithUs);
        profileFolder.setCreationDate(new Date());
        preCreatedCompanyAdquiredProfileFolderEvent.fire(profileFolder);
        companyAdquiredProfileFolderFacade.create(profileFolder);
        createdCompanyAdquiredProfileFolderEvent.fire(profileFolder);
        if(candidate.getCompanyAdquiredProfileList()==null){
            candidate.setCompanyAdquiredProfileList(new ArrayList<CompanyAdquiredProfile>());
        }
        if(company.getCompanyAdquiredProfileList()==null){
            company.setCompanyAdquiredProfileList(new ArrayList<CompanyAdquiredProfile>());
        }
        candidate.getCompanyAdquiredProfileList().add(profile);
        company.getCompanyAdquiredProfileList().add(profile);
        return "/views/candidate/NewEditCandidateView?faces-redirect=true";
    }
    
    public CompanyFolder createFolderWorkWithUs(Company company){
        CompanyFolder workWithUs= new CompanyFolder();
        workWithUs.setCompanyFolderType(companyFolderFacadeType.getWorkWithUsFolderType());
        workWithUs.setCreationDate(new Date());
        //obtenermo el mensaje
        FacesContext context=FacesContext.getCurrentInstance();
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        String workWithUsMesage=rb.getString("WorkWithUs");
        //setteamos el mensaje
        workWithUs.setDescription(workWithUsMesage);
        workWithUs.setIdCompany(company);
        workWithUs.setCompanyAdquiredProfileFolderList(new ArrayList<CompanyAdquiredProfileFolder>());
        workWithUs.setSearchList(new ArrayList<Search>());
        companyFolderFacade.create(workWithUs);        
        return workWithUs;
    }
    
    public void makeDirs(){
        File imagesDir=new File(ImageStoreHelper.pathToPersistentStore+candidate.getIdCandidate().toString()+"/"+"images");
        File videosDir=new File(ImageStoreHelper.pathToPersistentStore+candidate.getIdCandidate().toString()+"/"+"videos");
        imagesDir.mkdirs();
        videosDir.mkdirs();
    }
    
    private void persistCandidate() throws IOException{
        Date date = new Date();
        candidate.getUser().setCreationDate(date);
        candidate.getUser().setLastDate(date);
        candidate.getUser().setLogins(0);
        candidate.getUser().setActive(true);
        candidate.setLastModificationDate(date);
        candidate.setVisits(0);
        candidate.setCandidateEconomicType(candidateEconomicTypeFacade.find(1));
        candidate.setCandidateType(candidateTypeFacade.find(1));
        //String password=candidate.getUser().getPassword();
        try {
            candidate.getUser().setEmail(candidate.getUser().getEmail().toLowerCase());
            candidate.getUser().setPassword(Sha256Encrypter.getSha256(getCandidate().getUser().getPassword()));
        } catch (NoSuchAlgorithmException ex) {
//            Logger.getLogger(CreateCandidateBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(CreateCandidateBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        candidate.getUser().setCandidate(candidate);
        userFacade.create(candidate.getUser());
        //candidateFacade.create(candidate);
        //candidate.getUser().setCandidate(candidate);
        
        newUserEvent.fire(candidate.getUser());
        //candidateFacade.edit(candidate);
        newCandidateEvent.fire(candidate.getUser().getCandidate());
        //candidate.getUser().setPassword(password);
    }

    /**
     * @return the company
     */
    public Company getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(Company company) {
        this.company = company;
    }

    /**
     * @return the candidate
     */
    public Candidate getCandidate() {
        return candidate;
    }

    /**
     * @param candidate the candidate to set
     */
    public void setCandidate(Candidate candidate) {
        this.candidate = candidate;
    }
}
